package test.n00600;

public class Problem00610 {
    public static void main(String[] args) {
//        println(new int[]{1, 2, 3, 4, 5}, 2);
//        println(new int[]{0,1,2}, 4);
//        println(new int[]{}, 4);
        println(new int[]{1}, 1);
    }


    public static void println(int[] array, int k) {
        Solution s = new Solution();
        ListNode node = s.rotateRight(create(array), k);

        while (true) {
            System.out.print(node.val + ",");
            node = node.next;

            if (node == null) {
                System.out.println();
                break;
            }
        }
    }

    public static ListNode create(int[] a1) {
        if (a1.length == 0) {
            return null;
        }
        ListNode[] list = new ListNode[a1.length];
        for (int i = 0; i < a1.length; i++) {
            list[i] = new ListNode(a1[i]);
            if (i > 0) {
                list[i - 1].next = list[i];
            }
        }

        return list[0];
    }


    private static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    private static class Solution {
        /**
         * 给你一个链表的头节点 head ，旋转链表，将链表每个节点向右移动 k 个位置。
         *
         * 解题思路:
         *
         * 每次把最后一个节点放到最前面来
         * @param head
         * @param k
         * @return
         */
        public ListNode rotateRight(ListNode head, int k) {
            int len = getNodeLength(head);
            if (len <= 1 || k % len == 0) {
                return head;
            }
            k = k % len;
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            ListNode curr = head;
            while (k > 0) {
                while (curr.next.next != null) {
                    curr = curr.next;
                }
                curr.next.next = dummy.next;
                dummy.next = curr.next;
                curr.next = null;
                curr = dummy.next;
                k--;
            }
            return dummy.next;
        }

        private int getNodeLength(ListNode head) {
            ListNode t = head;
            int len = 0;
            while (t != null) {
                t = t.next;
                len++;
            }
            return len;
        }
    }
}
